package com.liy.framework.common.jwt;

import com.liy.framework.common.extvo.LoginInfo;
import com.liy.framework.common.utils.JSONUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JWTHelper {
    private static RsaKeyHelper rsaKeyHelper = new RsaKeyHelper();
    private static String USER_KEY = "USER";

    public JWTHelper() {
    }

    public static String generateToken(LoginInfo jwtInfo, String priKeyPath, int expire) throws Exception {
        String compactJws = Jwts.builder().setSubject(jwtInfo.getAccount()).claim("userId", jwtInfo.getId()).claim("name", jwtInfo.getName()).claim("loginIp", jwtInfo.getLoginIp()).signWith(SignatureAlgorithm.RS256, rsaKeyHelper.getPrivateKey(priKeyPath)).compact();
        return compactJws;
    }

    public static String generateToken(LoginInfo jwtInfo, byte[] priKey, int expire) throws Exception {
        String loginUserJsonStr = JSONUtils.object2Json(jwtInfo);
        String compactJws = Jwts.builder().setSubject(jwtInfo.getAccount()).claim(USER_KEY, loginUserJsonStr).signWith(SignatureAlgorithm.RS256, rsaKeyHelper.getPrivateKey(priKey)).compact();
        return compactJws;
    }

    public static Jws<Claims> parserToken(String token, String pubKeyPath) throws Exception {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(rsaKeyHelper.getPublicKey(pubKeyPath)).parseClaimsJws(token);
        return claimsJws;
    }

    public static Jws<Claims> parserToken(String token, byte[] pubKey) throws Exception {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(rsaKeyHelper.getPublicKey(pubKey)).parseClaimsJws(token);
        return claimsJws;
    }

    public static LoginInfo getInfoFromToken(String token, String pubKeyPath) throws Exception {
        Jws<Claims> claimsJws = parserToken(token, pubKeyPath);
        Claims body = (Claims)claimsJws.getBody();
        String str = body.get(USER_KEY).toString();
        return (LoginInfo)JSONUtils.json2Object(str, LoginInfo.class);
    }

    public static LoginInfo getInfoFromToken(String token, byte[] pubKey) throws Exception {
        Jws<Claims> claimsJws = parserToken(token, pubKey);
        Claims body = (Claims)claimsJws.getBody();
        String str = body.get(USER_KEY).toString();
        return (LoginInfo)JSONUtils.json2Object(str, LoginInfo.class);
    }

    public static void main(String[] args) {
        String jk = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsInVzZXJJZCI6IjkwMCIsImFjY291bnQiOiJhZG1pbiIsIm5hbWUiOiLnrqHnkIblkZgiLCJsb2dpbklwIjoiMTAuMTQ2LjM4LjE4OCIsInVzZXJUeXBlIjoiQ1pZIiwic3RhdGlvbk5vIjoiMjQxMDE3Iiwic3RhdGlvbk5hbWUiOiLlrp3lronnq5kifQ.BhA960tipDOuVgseGIfaXIAOe1RqvO_Zp7ZbYYvM8ahEgcPBpbArDM1RFdOBHoaE9YYS1j5DF-BgaMbveoahGhhOp6ivWF1ug5l4EjlFt6aSTjvzxHdH3KHDhqlkmh0E8NYhnyYP-GTRK_Bhxx2ksWNFjg1kqw-jp1T7SLRcrKY";
    }
}
